import { Modal, message } from 'antd'
const confirm = Modal.confirm;
import { WeaTools, WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import {i18n} from '../public/i18n';
import * as mobx from 'mobx';
import loadjs from 'loadjs';

import LoginPluginFactory from './plugin/loginPluginFactory';
const { ua } = WeaTools;
const isIE9 = (ua.browser === "IE");

const toJS = mobx.toJS;
let remindNum = 0;

const getLoginForm = (params) => {
    let { langid, callback,queryParams } = params;
    window.currLanguageId = langid;
    let loginid = params.loginid || '';
    if (loginid == '') {
        loginid = jQuery('#loginid').val();
    }

    let loginFormItems = [];
    let loginFormHiddenItems = [];
    let loginSetting = {};
    let qrCode = {};
    let hasMultiLang = false;

    loginFormItems = [
        { label: '账号', atype: 'account', id: 'loginid', name: 'loginid', type: 'text' },
        { label: '密码', atype: 'password', id: 'userpassword', name: 'userpassword', type: 'password'},
    ];
	
	queryParams = queryParams && toJS(queryParams);
    if((queryParams && queryParams.appid && queryParams.service && queryParams.message)){
        if(remindNum==0){
			remindNum = remindNum+1;
			WeaTools.callApi('/api/integration/common1/getMessageByCode','POST',
			{code:queryParams.message,language:langid}).then((rs)=>{
				 message.error(rs.message, 3);
			}).catch(err=>{
				if(console) console.log(err) ;
			})
		}
    }
	
    WeaTools.callApi('/api/hrm/login/getLoginForm', 'POST', { loginid, langid }).then((result) => {
        // loginFormItems = [
        //     {label: '账号', atype: 'account', id: 'loginid', name: 'loginid', type: 'text'},
        //     {label: '密码', atype: 'password', id: 'userpassword', name: 'userpassword', type: 'password'},
        //     {label: '验证码', atype: 'validatecode', id: 'validatecode', name: 'validatecode', type: 'text'},
        //     {label: '动态令牌口令', atype: 'common', id: 'tokenAuthKey', name: 'tokenAuthKey', type: 'text'}
        // ];
        loginFormItems = result.formItems;
        loginSetting = result.loginSetting;
        qrCode = result.qrcode;
        hasMultiLang = loginSetting.hasMultiLang;
        loginFormHiddenItems = [
            { html: '<input type="hidden" id="messages" name="messages" value="">' }
        ];
        
        new LoginPluginFactory().getLocalPlugin(result,()=>{
            window.loginPlugin && window.loginPlugin.init() ;
        })

        if (callback && typeof callback == 'function') callback({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting,qrCode });
    }).catch((err) => {
        message.error(err);
        if (callback && typeof callback == 'function') callback({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting,qrCode });
    });
};

const login = (params) => {
    const {openRSA} = params.loginSetting;
    if(openRSA && openRSA=='1'){//启用RSA加密
        __RSAEcrypt__.refreshRsaCode(function(){
            loginSync(params);
        });
    }else{
        loginSync(params);
    }
};

const loginSync = (params) => {
    const { userUsbType, hasMultiLang, hasValidateCode, 
           validateCodeKey,numValidateWrong, validateType, 
           showDynamicPwd,openRSA} = params.loginSetting;
    let { langid, success, failure, logintype, queryParams} = params;
    const loginid = jQuery('#loginid').val();
    let userpassword = jQuery('#userpassword').val();
    let dynamicPassword = jQuery('#dynamicPassword').val();
    let loginidRsa = loginid ;
    let userpasswordRsa = userpassword;
    if(openRSA && openRSA=='1'){//启用RSA加密
        userpasswordRsa = __RSAEcrypt__.rsa_data_encrypt(userpassword);
        loginidRsa = __RSAEcrypt__.rsa_data_encrypt(loginid) ;
    }
    const tokenAuthKey = jQuery('#tokenAuthKey') ? jQuery('#tokenAuthKey').val() : '';
    const validatecode = jQuery('#validatecode') ? jQuery('#validatecode').val() : '';
    const messages = jQuery('#messages') ? jQuery('#messages').val() : '';
    message.destroy();
    if(jQuery('#userpassword') && jQuery('#userpassword').length>0){
        if (loginid == '' || userpassword == '') {
            message.error(getLabel('386478',"请输入用户名、密码"), 3);
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }
    if(jQuery('#dynamicPassword') && jQuery('#dynamicPassword').length>0){
        if(dynamicPassword==''){
            message.error(getLabel('20289',"请输入动态密码"), 3);
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    if (hasValidateCode && validatecode == '') {
        message.error(getLabel('84270',"请输入验证码"), 3);
        if (failure && typeof failure == 'function') failure();
        return;
    }

    if (userUsbType == '3') {
        if (tokenAuthKey == '') {
            message.warning(getLabel('84271',"请输入动态令牌口令"));
            if (failure && typeof failure == 'function') failure();
            return;
        } else if (!isdigit(tokenAuthKey) || tokenAuthKey.length != 6) {
            message.warning(getLabel('386435',"动态令牌口令必须为6位数字！"));
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    queryParams = toJS(queryParams);
    if(queryParams && queryParams.appid && queryParams.service){
        queryParams.loginid=loginid;
        queryParams.userpassword=userpasswordRsa;
		queryParams.isRememberAccount = params.isRememberAccount ? '1':'0' ;
        queryParams.isRememberPassword = params.isRememberPassword ? '1':'0' ;
		queryParams.validatecode=validatecode;
        queryParams.validateCodeKey=validateCodeKey ;
        queryParams.languid=langid ;
        let tmps = [];  
        jQuery("body").append("<form name='ssoForm'></form>");
        let form = jQuery("form[name='ssoForm']")
        form.attr("action", '/login/VerifyLoginWeaversso.jsp');
        form.attr("method", "post");
        form.attr("style", "display:none");
        for (let key in queryParams) {  
            form.append("<input type='text' name='" + key + "' value = '" + queryParams[key] + "'></input>");
        }  
        //跳转到sso
        form.submit();
        return;
    }

    const {plugin} = params 

    const checkWeakPassword = (nCallback) => {
        WeaTools.callApi('/api/hrm/password/isWeakPassword', 'POST', {
            password: userpasswordRsa
        }).then(datas => {
            const {
                weakPasswordDisable,
                isWeakPassword
            } = datas;

            if (isWeakPassword && (weakPasswordDisable === "1")) {
                confirm({
                    title: getLabel(131329, '信息确认'),
                    content: getLabel('516219','该密码安全性较低，管理员已开启弱密码禁止保存设置，请修改密码。'),
                    onOk() {
                        showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password`, { width: 800, height: 500 },"",()=>failure({reflashValidateCode:true}));
                    },
                    onCancel() {
                        failure({reflashValidateCode:true});
                        WeaTools.callApi('/api/hrm/login/checkLogout','POST');
                    },
                });

                // const url = `/spa/hrm/index_mobx.html#/main/hrm/weakPassConfirm`;
                // const dialog = ecCom.WeaTools.createDialog({
                //     url,
                //     title: getLabel(131329, '信息确认'),
                //     icon:"icon-coms02-Warning",
                //     iconBgcolor:"#ff9900",
                //     style: {
                //         width: 380,
                //         height: 161
                //     },
                //     onCancel: ()=>{
                //         failure({reflashValidateCode:true});
                //         WeaTools.callApi('/api/hrm/login/checkLogout','POST');
                //     },
                //     callback:() => {
                //         showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password`, { width: 800, height: 500 },"",()=>failure({reflashValidateCode:true}));
                //     },
                // });
                // dialog.show();
            } else {
                nCallback();
            }
        }).catch(() => {
             nCallback();
        })
    }

    WeaTools.callApi('/api/hrm/login/checkLogin', 'POST', {
        islanguid: langid,
        loginid: loginidRsa,
        userpassword: userpasswordRsa,
        dynamicPassword:dynamicPassword,
        tokenAuthKey: tokenAuthKey,
        validatecode: validatecode,
        validateCodeKey:validateCodeKey,
        logintype: logintype,
        messages: messages,
        isie: isIE9,
        ...plugin
    }).then((result) => {
        if ('access_token' in result && typeof result.access_token === 'string' && result.access_token !== '') {
            localStorage.setItem('access_token', result.access_token);
        } else {
            localStorage.access_token && localStorage.removeItem('access_token');
        }

        if(result.user_token && result.user_token!=''){
            userpassword = result.user_token;
        }

        if (result.loginstatus == 'true') {
            if (success && typeof success == 'function') {
                message.destroy();
                if(logintype==2){
                    checkWeakPassword(()=>success(loginid, userpassword, result));
                }else{
                    WeaTools.callApi('/api/hrm/login/remindLogin', 'POST', {logintype: logintype}).then((result) => {
                        if (result.status == '1') {
                            if (result.isUpPswd == 'true') {
                                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                confirm({
                                    title: i18n.confirm.systemhints(),
                                    content: getLabel('81626',"首次登录需修改密码！"),
                                    onOk() {
                                        if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                        showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password?optype=2`, { width: 800, height: 500 });
                                        return;
                                    },
                                    onCancel() {
                                        if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                        WeaTools.callApi('/api/hrm/login/checkLogout', 'POST', {}).then((result) => { });
                                        return;
                                    },
                                });
                            } else {
                                if (result.passwdReminder == '1') {
                                    if (result.canpass == '1') {
                                        if (result.canremind == '1') {
                                            const content = getLabel('386479',"您的密码还有{params}天过期,是否现在修改?").replace('{params}', result.passwdelse);
                                            confirm({
                                                title: i18n.confirm.systemhints(),
                                                content,
                                                onOk() {
                                                    if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                                    showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password`, { width: 800, height: 500 });
                                                    return;
                                                },
                                                onCancel() {
                                                    checkWeakPassword(()=>success(loginid, userpassword, result));
                                                },
                                            });
                                        } else {
                                            checkWeakPassword(()=>success(loginid, userpassword, result));
                                        }
                                    } else {
                                        confirm({
                                            title: i18n.confirm.systemhints(),
                                            content: getLabel('386480',"您的密码已经过期,请立即修改！"),
                                            onOk() {
                                                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                                showDialog("", `/spa/hrm/index_mobx.html#/main/hrm/password?optype=1`, { width: 800, height: 500 });
                                                return;
                                            },
                                            onCancel() {
                                                if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                                                WeaTools.callApi('/api/hrm/login/checkLogout', 'POST', {}).then((result) => { });
                                                return;
                                            },
                                        });
                                    }
                                } else {
                                    checkWeakPassword(()=>success(loginid, userpassword, result));
                                }
                            }
                        }
                    });
                }
            }
        } else {
            if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
            message.destroy();
            let errorMsg = result.msg || getLabel('386481',"登录失败");
            let errorUrl = '';
            let errorText = '';

            if (result.msgcode == '120') {
                errorUrl = '/spa/hrm/index_mobx.html#/main/hrm/BindTokenKey?langid='+langid;
                errorText = getLabel('386125',"令牌绑定");
            } else if (result.msgcode == '122') {
                errorUrl = '/spa/hrm/index_mobx.html#/main/hrm/BindTokenKey?syncTokenKey=1&langid='+langid;
                errorText = getLabel('129202',"令牌同步");
            } else if (result.msgcode == '19') {
				if(result.msg) message.warning(result.msg);
                window.doLicenseSubmit && window.doLicenseSubmit();
                return;
            }

            // 返回错误信息提示
            message.error((
                <span>
                    {errorMsg}
                    {errorUrl ? (
                        <span style={{ marginLeft: '5px', color: '#00a9ff', cursor: 'pointer' }} onClick={() => showDialog('', errorUrl, { width: 800, height: 465 })}>{errorText}</span>
                    ) : ''
                    }
                </span>
            ), 5);
        }
    });

};

const getDynamicPassword = (params) => {
    let { langid, success, failure} = params;
    const {openRSA} = params.loginSetting;
    const loginid = jQuery('#loginid').val();
    const userpassword = jQuery('#userpassword').val();
    const dynamicPassword = jQuery('#dynamicPassword').val();

    message.destroy();
    if(jQuery('#userpassword') && jQuery('#userpassword').length>0){
        if (loginid == '' || userpassword == '') {
            message.error(getLabel('386478',"请输入用户名、密码"), 3);
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    if(openRSA && openRSA=='1'){//启用RSA加密
        __RSAEcrypt__.refreshRsaCode(function(){
            getDynamicPasswordSync(params);
        });
    }else{
        getDynamicPasswordSync(params);
    }
};

const getDynamicPasswordSync = (params) => {
    let {langid, success, failure} = params;
    const {openRSA} = params.loginSetting;
    let loginid = jQuery('#loginid').val();
    let userpassword = jQuery('#userpassword').val();
    let loginidRsa = loginid;
    let userpasswordRsa = userpassword;
    if(openRSA && openRSA=='1'){//启用RSA加密
        loginidRsa = __RSAEcrypt__.rsa_data_encrypt(loginid) ;
        userpasswordRsa = __RSAEcrypt__.rsa_data_encrypt(userpassword);
    }

    WeaTools.callApi('/api/hrm/login/getDynamicPassword','POST',{
        langid: langid,
        loginid: loginidRsa,
        userpassword: userpasswordRsa,
    }).then((result) => {
        if (result.status == '1') {
            if (success && typeof success == 'function') {
                success(result);
            }
        } else {
            message.destroy();
            let errorMsg = result.message;
            // 返回错误信息提示
            message.error((
                <span>
                    {errorMsg}
                </span>
            ), 5);
        }
    });
};

const showDialog = (title, url, style, callback, onCancel) => {
    style=style||{ width: 800, height: 465 };
    const dialog = ecCom.WeaTools.createDialog({ moduleName: 'hrm', title, url, style, callback, onCancel });
    dialog.show();
};

const isdigit = (s) => {
    var r, re;
    re = /\d*/i; //\d表示数字,*表示匹配多个数字
    r = s.match(re);
    return (r == s) ? true : false;
}

// 提供登录相关的全局方法
window.doLoginAction = (actionName, params) => {
    if (actionName == 'getLoginForm') {
        const { langid } = params; 
        WeaLocaleProvider.getLocaleLabelByLang(['common', 'hrm'], langid).then(()=>{
            getLoginForm(params);
        });
    } else if (actionName == 'login') {
        //异步加载ras文件
        loadjs.isDefined('rsa') ? loadjs.ready('rsa', ()=>{
            window.loginPlugin.willLogin(params,login)
            //login(params)
        }) : loadjs(["/js/rsa/jsencrypt.js","/js/rsa/rsa.js"], 'rsa', {
            async: false,
            success: ()=>{
                window.loginPlugin.willLogin(params,login)
                //login(params)
            }
        });
    } else if (actionName == 'getDynamicPassword') {
        loadjs.isDefined('rsa') ? loadjs.ready('rsa', () => {
            getDynamicPassword(params);
        }) : loadjs(["/js/rsa/jsencrypt.js", "/js/rsa/rsa.js"], 'rsa', {
            async: false,
            success: () => {
                getDynamicPassword(params);
            }
        });
    } else if(actionName == 'forgetPassword'){
        const url = `/spa/hrm/index_mobx.html#/main/hrmSingle/forgetPassword?langid=${window.currLanguageId}`;//`/#/main/hrm/forgetPassword?langid=${window.currLanguageId}`;//`/spa/hrm/index_mobx.html#/main/hrm/forgetPassword?langid=${window.currLanguageId}`
        showDialog(getLabel('127899',"找回密码"), url, { width: 600, height: 245 }, data => {
            if(data){
                const {status} = data;
                if(status == '1'){
                    message.success(data.message || getLabel(83551, '保存成功！'))
                }else{
                    message.error(data.message);
                }
                //解决登录页忘记密码保存成功后，不能输入账号和密码的问题。
                setTimeout(() => {
                    $(".fade-leave").css({display:"none"})
                })
            }
        });
    }
};
//window.doLoginAction('forgetPassword')